package com.example.huajia.wx.controller;

import com.example.huajia.wx.common.util.R;
import com.example.huajia.wx.common.util.SnowFlakeGenerateIdWorker;
import com.example.huajia.wx.config.shiro.JwtUtil;
import com.example.huajia.wx.controller.form.InsertOrderForm;
import com.example.huajia.wx.controller.form.SearchMyOrderForm;
import com.example.huajia.wx.exception.HJException;
import com.example.huajia.wx.service.OrderService;
import com.example.huajia.wx.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.example.huajia.wx.common.util.RedisKey.ORDER_MINE_KEY;
import static com.example.huajia.wx.common.util.RedisKey.PRODUCT_ALL_KEY;

@RestController
@RequestMapping("/order")
@Api("订单接口")
public class OrderController {
    @Resource
    private OrderService orderService;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("/insertOrder")
    @ApiOperation("添加订单接口")
    @Transactional
    public R insertOrder(@Valid @RequestBody InsertOrderForm form, @RequestHeader("token") String token){
        SnowFlakeGenerateIdWorker snowFlakeGenerateIdWorker = new SnowFlakeGenerateIdWorker(0L, 0L);
        int userId = jwtUtil.getUserId(token);
        String address = form.getAddress();
        String name = form.getName();
        String phone = form.getPhone();
        String productCount = form.getProductCount();
        String productId = form.getProductId();
        String productName = form.getProductName();
        String productPoint = form.getProductPoint();
        String totalPoint = form.getTotalPoint();
        String img = form.getImg();
        String id = snowFlakeGenerateIdWorker.generateNextId();
        String orderNo = snowFlakeGenerateIdWorker.generateNextId();
        HashMap map = new HashMap();
        map.put("userId", userId);
        map.put("address", address);
        map.put("name", name);
        map.put("phone", phone);
        map.put("productCount", productCount);
        map.put("productId", productId);
        map.put("productName", productName);
        map.put("productPoint", productPoint);
        map.put("totalPoint", totalPoint);
        map.put("id", id);
        map.put("orderNo", orderNo);
        map.put("img", img);
        int row1 = orderService.insertOrder(map);
        if (row1 == 0){
            throw new HJException("新增订单失败！");
        }
        String key = PRODUCT_ALL_KEY;
        //更新库存数量
        HashMap map1 = new HashMap();
        map1.put("stock", productCount);
        map1.put("id", productId);
        int row2 = orderService.updateStock(map1);
        if (row2 == 0){
            throw new HJException("更新库存失败！");
        }
        redisTemplate.expire(key, 0L, TimeUnit.SECONDS);
        //更新用户积分
        HashMap map2 = new HashMap();
        map2.put("id", userId);
        map2.put("point", productPoint);
        int row3 = userService.updateUserPoint(map2);
        if (row3 == 0){
            throw new HJException("用户积分更新失败！");
        }
        return R.ok();
    }

    @PostMapping("/searchMyOrder")
    @ApiOperation("查询我的订单接口")
    public R searchMyOrder(@Valid @RequestBody SearchMyOrderForm form, @RequestHeader("token") String token){
        int userId = jwtUtil.getUserId(token);
        Integer length = form.getLength();
        Integer page = form.getPage();
        long start = (page - 1) * length;
        long end = start + length - 1;
        //先判断redis里面是否存在数据
        String key = ORDER_MINE_KEY + userId;
        List range = redisTemplate.opsForList().range(key, start, end);
        if (!range.isEmpty()){
            return R.ok().put("result", range);
        }
        HashMap map = new HashMap();
        map.put("userId", userId);
        map.put("start", start);
        map.put("length", length);
        ArrayList<HashMap> list = orderService.searchMyOrder(map);
        return R.ok().put("result", list);
    }
}
